from django_redis import get_redis_connection
import base64
import pickle


def merge_cookie_redis_cart(request, respon, user):
    """
    1.cookie与redis都有，cookie覆盖redis
    2.cookie有，redis没有，redis新增
    """

    cook_str = request.COOKIES.get('cart')
    if not cook_str:
        return respon

    cook_dic = pickle.loads(base64.b64decode(cook_str.encode()))
    redis_conn = get_redis_connection('carts')
    for sku_id, item in cook_dic.items():
        redis_conn.hset('cart_%d' % user.id, sku_id, item['count'])
        if item['selected']:
            redis_conn.sadd('selected_%d' % user.id, sku_id)
        else:
            redis_conn.srem('selected_%d' % user.id, sku_id)

    respon.delete_cookie('cart')

    return respon
